#ifdef USE_SD
#include <logger_rte.h>
#include <STM32SD.h>
#include "SDC.h"

#ifndef SD_DETECT_PIN
#define SD_DETECT_PIN SD_DETECT_NONE
#endif

int SDC::begin() {
    if (!card.init(SD_DETECT_PIN)) {
        logger.debug("initialization failed. Is a card inserted?");
        delay(10);
    }
    switch (card.type()) {
        case SD_CARD_TYPE_SD1:
            logger.debug("SD1");
            break;
        case SD_CARD_TYPE_SD2:
            logger.debug("SD2");
            break;
        case SD_CARD_TYPE_SDHC:
            logger.debug("SDHC");
            break;
        default:
            logger.debug("Unknown");
    }
    // Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32
    if (!fatFs.init()) {
        logger.debug("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card");
        return -1;
    }

    // print the type and size of the first FAT-type volume
    uint64_t volumesize;
    logger.debug("\nVolume type is FAT%d", fatFs.fatType());

    volumesize = fatFs.blocksPerCluster(); // clusters are collections of blocks
    volumesize *= fatFs.clusterCount();    // we'll have a lot of clusters
    volumesize *= 512;                     // SD card blocks are always 512 bytes
    logger.debug("Volume size (bytes): %d", volumesize);
    volumesize /= 1024;
    logger.debug("Volume size (Kbytes): %d", volumesize);
    volumesize /= 1024;
    logger.debug("Volume size (Mbytes): %d", volumesize);

    logger.debug("\nFiles found on the card (name, date and size in bytes): ");
    File root = SD.openRoot();

    // list all files in the card with date and size
    root.ls(LS_R | LS_DATE | LS_SIZE);
    root.close();
    logger.debug("###### End of the SD tests ######");
    return 0;
}
#endif